const axios = require('axios');

class GitLabAPI {
  constructor(baseURL, accessToken) {
    this.baseURL = baseURL.replace(/\/$/, ''); // 移除末尾的斜杠
    this.accessToken = accessToken;
    this.client = axios.create({
      baseURL: this.baseURL,
      headers: {
        'Private-Token': accessToken,
        'Content-Type': 'application/json'
      },
      timeout: 30000 // 30秒超时
    });
  }

  /**
   * 测试GitLab连接
   */
  async testConnection() {
    try {
      console.log('测试GitLab连接:', this.baseURL);
      const response = await this.client.get('/api/v4/user');
      console.log('GitLab连接成功，用户:', response.data.username);
      return {
        success: true,
        user: response.data
      };
    } catch (error) {
      console.error('GitLab连接失败:', {
        url: this.baseURL,
        error: error.message,
        code: error.code,
        response: error.response?.data
      });
      return {
        success: false,
        error: error.message,
        details: {
          code: error.code,
          response: error.response?.data
        }
      };
    }
  }

  /**
   * 获取项目信息
   */
  async getProject(projectPath) {
    try {
      const encodedPath = encodeURIComponent(projectPath);
      const response = await this.client.get(`/api/v4/projects/${encodedPath}`);
      return response.data;
    } catch (error) {
      throw new Error(`获取项目信息失败: ${error.message}`);
    }
  }

  /**
   * 获取项目的提交记录
   * @param {string} projectPath - 项目路径 (如: username/project)
   * @param {Object} options - 选项
   * @param {string} options.since - 开始日期 (ISO格式)
   * @param {string} options.until - 结束日期 (ISO格式)
   * @param {number} options.per_page - 每页数量 (最大100)
   * @param {number} options.page - 页码
   */
  async getCommits(projectPath, options = {}) {
    try {
      const encodedPath = encodeURIComponent(projectPath);
      const params = {
        since: options.since,
        until: options.until,
        per_page: options.per_page || 100,
        page: options.page || 1,
        with_stats: true
      };

      // 移除空值参数
      Object.keys(params).forEach(key => {
        if (params[key] === undefined || params[key] === null) {
          delete params[key];
        }
      });

      const response = await this.client.get(`/api/v4/projects/${encodedPath}/repository/commits`, { params });
      
      // 获取完整的提交信息
      const commitsWithDetails = await Promise.all(
        response.data.map(async (commit) => {
          try {
            const detailResponse = await this.client.get(`/api/v4/projects/${encodedPath}/repository/commits/${commit.id}`);
            return {
              ...commit,
              stats: detailResponse.data.stats,
              files: detailResponse.data.files
            };
          } catch (error) {
            console.warn(`获取提交详情失败: ${commit.id}`, error.message);
            return commit;
          }
        })
      );

      return {
        commits: commitsWithDetails,
        totalPages: response.headers['x-total-pages'] || 1,
        totalItems: response.headers['x-total'] || commitsWithDetails.length
      };
    } catch (error) {
      throw new Error(`获取提交记录失败: ${error.message}`);
    }
  }

  /**
   * 获取所有提交记录（自动分页）
   */
  async getAllCommits(projectPath, options = {}) {
    const allCommits = [];
    let page = 1;
    let hasMore = true;

    while (hasMore) {
      const result = await this.getCommits(projectPath, {
        ...options,
        page,
        per_page: 100
      });

      allCommits.push(...result.commits);
      
      if (page >= result.totalPages) {
        hasMore = false;
      } else {
        page++;
        // 添加延迟避免API限制
        await new Promise(resolve => setTimeout(resolve, 100));
      }
    }

    return allCommits;
  }

  /**
   * 获取项目成员
   */
  async getProjectMembers(projectPath) {
    try {
      const encodedPath = encodeURIComponent(projectPath);
      const response = await this.client.get(`/api/v4/projects/${encodedPath}/members`);
      return response.data;
    } catch (error) {
      throw new Error(`获取项目成员失败: ${error.message}`);
    }
  }

  /**
   * 获取项目分支
   */
  async getBranches(projectPath) {
    try {
      const encodedPath = encodeURIComponent(projectPath);
      const response = await this.client.get(`/api/v4/projects/${encodedPath}/repository/branches`);
      return response.data;
    } catch (error) {
      throw new Error(`获取分支失败: ${error.message}`);
    }
  }

  /**
   * 获取项目标签
   */
  async getTags(projectPath) {
    try {
      const encodedPath = encodeURIComponent(projectPath);
      const response = await this.client.get(`/api/v4/projects/${encodedPath}/repository/tags`);
      return response.data;
    } catch (error) {
      throw new Error(`获取标签失败: ${error.message}`);
    }
  }

  /**
   * 获取文件内容
   */
  async getFileContent(projectPath, filePath, ref = 'main') {
    try {
      const encodedPath = encodeURIComponent(projectPath);
      const encodedFilePath = encodeURIComponent(filePath);
      const response = await this.client.get(`/api/v4/projects/${encodedPath}/repository/files/${encodedFilePath}/raw`, {
        params: { ref }
      });
      return response.data;
    } catch (error) {
      throw new Error(`获取文件内容失败: ${error.message}`);
    }
  }
}

module.exports = GitLabAPI;